package com.tiniplanet.webgate.web.controller;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.tiniplanet.webgate.entity.Employee;
import com.tiniplanet.webgate.service.EmployeeService;

@Controller
public class UserController extends PageController {
	private static final Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	EmployeeService employeeService;

	public UserController() {
		addItemToTabMenu("/news", "News", "dashboard", false);
		addItemToTabMenu("report", "Report", "reports", false);

		addItemToSideMenu("/home", "General", "home", false);
		addItemToSideMenu("/admin/", "Admin", "form", false);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/userinfo")
	public ModelAndView setupUserList(ModelMap modelMap, @RequestParam String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.debug("prepare user list");

		Map<Integer, String> gender = new LinkedHashMap<Integer, String>();
		gender.put(0, "Male");
		gender.put(1, "Female");

		Employee employee = employeeService.getById(id);
		map.put("empl", employee);
		map.put("gender", gender);
		map.put("sideMenu", sideMenu);
		map.put("tabMenu", tabMenu);

		return new ModelAndView("userinfo", map);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addEmployee(@ModelAttribute("employee") Employee data, BindingResult result) {
		Employee employee = employeeService.getById(data.getId());

		// update data
		employee.setFirstName(data.getFirstName());
		employee.setMiddleName(data.getMiddleName());
		employee.setLastName(data.getLastName());

		employeeService.save(employee);
		return "redirect:/home";
	}

}
